import React, { useState, useEffect, useCallback } from "react";

function usePollingAndSubmit(
  submitAPI: () => Promise<{ requestId: string }>,
  pollingAPI: (id: string) => Promise<any>
) {
  const [data, setData] = useState<any>(null);
  const [isPolling, setIsPolling] = useState<boolean>(false);

  const submitAndStartPolling = useCallback(async () => {
    // 提交操作
    const response = await submitAPI();
    const requestId = response.requestId;

    if (!requestId) return;

    setIsPolling(true);
    const intervalId = setInterval(async () => {
      const result = await pollingAPI(requestId);
      if (result !== null) {
        setData(result);
        clearInterval(intervalId);
        setIsPolling(false);
      }
    }, 3000);

    return () => clearInterval(intervalId);
  }, [submitAPI, pollingAPI]);

  return { data, isPolling, submitAndStartPolling };
}

export const ImgSelection = () => {
  // 假设submitAPI和pollingAPI是已定义的异步函数
  const submitAPI = async () => {
    // 模拟API调用
    return new Promise<{ requestId: string }>((resolve) =>
      setTimeout(() => resolve({ requestId: "12345" }), 1000)
    );
  };

  const pollingAPI = async (id: string) => {
    // 模拟轮询API调用
    return new Promise<any>((resolve) =>
      setTimeout(
        () => resolve(id === "12345" ? { status: "completed" } : null),
        1000
      )
    );
  };

  const { data, isPolling, submitAndStartPolling } = usePollingAndSubmit(
    submitAPI,
    pollingAPI
  );

  return (
    <div>
      <button onClick={submitAndStartPolling}>提交并开始轮询</button>
      <div>任务状态: {isPolling ? "轮询中..." : JSON.stringify(data)}</div>
    </div>
  );
};
